package com.cuanbo.dualscreenteachzhu.widget;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.cuanbo.dualscreenteachzhu.R;

public class UIWindow {

    private final Context mContext;
    private final WindowManager mWindowManager;
    private View rootView;
    private WindowManager.LayoutParams params;

    public UIWindow(Context context){
        // 获取应用的Context
        mContext=context.getApplicationContext();
        // 获取WindowManager
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        initView();
    }

    private void initView() {
        rootView = LayoutInflater.from(mContext).inflate(R.layout.uiwindow_layout, null);

    }

    public void show(){
        try{
            mWindowManager.removeView(rootView);
        }catch (Exception e){}
        params = new WindowManager.LayoutParams();
        // 类型 Build.VERSION_CODES.M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            //TYPE_SYSTEM_ALERT
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        // 设置flag
        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
        params.flags = flags;
        // 不设置这个弹出框的透明遮罩显示为黑色
        params.format = PixelFormat.TRANSLUCENT;
        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
        // 不设置这个flag的话，home页的划屏会有问题
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        mWindowManager.addView(rootView, params);
    }

}
